import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Alert, Platform } from 'react-native';
import NetInfo from '@react-native-community/netinfo';

const NetworkDemo = () => {
  const [networkState, setNetworkState] = useState({
    isConnected: false,
    type: 'unknown',
    details: {},
  });

  // 初始化获取网络状态
  useEffect(() => {
    const unsubscribe = NetInfo.addEventListener((state) => {
      setNetworkState(state);
      // 网络变化时弹窗提示（可选）
      if (Platform.OS === 'android') {
        Alert.alert('网络状态变化', `当前连接类型：${state.type}`);
      }
    });

    // 初始获取状态
    NetInfo.fetch().then(state => setNetworkState(state));

    return () => unsubscribe();
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>网络状态检测</Text>
      <View style={styles.infoBox}>
        <Text>是否连接: {networkState.isConnected ? '是' : '否'}</Text>
        <Text>连接类型: {networkState.type}</Text>
        {networkState.type === 'wifi' && (
          <Text>WiFi 名称: {networkState.details?.ssid || '未知'}</Text>
        )}
        {networkState.type === 'cellular' && (
          <Text>运营商: {networkState.details?.carrierName || '未知'}</Text>
        )}
        <Text>IPv4 地址: {networkState.details?.ipAddress || '无'}</Text>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 20,
    marginBottom: 20,
    fontWeight: 'bold',
  },
  infoBox: {
    backgroundColor: '#f0f8ff',
    padding: 15,
    borderRadius: 8,
    width: '80%',
    textAlign: 'center',
  },
});

export default NetworkDemo;